package com.victor.bookretail.service;

import cn.hutool.json.JSONUtil;
import com.victor.bookretail.common.ResultCode;
import com.victor.bookretail.domain.OrderInfoBo;
import com.victor.bookretail.domain.OrderInfoSearchBo;
import com.victor.bookretail.entity.OrderInfoPo;
import com.victor.bookretail.exception.BusinessException;
import com.victor.bookretail.repository.OrderInfoRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderService {

    @Resource
    private OrderInfoRepository orderInfoRepository;

    @Resource
    private UserService userService;

    @Resource
    private TransactionTemplate transactionTemplate;

    public OrderInfoBo createOrder(OrderInfoBo orderInfoBo) {
        try {
            OrderInfoPo po = transactionTemplate.execute(status -> {
                OrderInfoPo orderInfoPo = orderInfoRepository.insert(OrderInfoPo.fromBo(orderInfoBo));
                userService.updateUserPoint(orderInfoPo.toBo());
                return orderInfoPo;
            });
            return Objects.isNull(po) ? null : po.toBo();
        } catch (Exception e) {
            log.error("Failed to create order. input order info:{}",
                    JSONUtil.toJsonStr(orderInfoBo), e);
            throw new BusinessException(ResultCode.FAILED_CREATE_ORDER);
        }
    }

    public List<OrderInfoBo> queryOrderList(OrderInfoSearchBo searchBo) {
        return orderInfoRepository.query(searchBo).stream()
                .map(OrderInfoPo::toBo)
                .collect(Collectors.toList());
    }


}
